﻿using Cxuu.Common;
using Cxuu.Models;
using Cxuu.Service;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Text.Json;
using System.Threading.Tasks;

namespace Cxuu.Web.Admin
{
    [Area("Admin")]
    [Authorize]
    public class ConfigController : Base
    {
        private readonly ConfigService _configService;
        private readonly LogService _logService;
        public ConfigController(ConfigService configService, LogService logService)
        {
            _configService = configService;
            _logService = logService;
        }


        public async Task<IActionResult> Index()
        {
            return View(await _configService.GetByNameAsync());
        }


        [HttpPost]
        [XssFieldFilter]//防Xss
        public async Task<IActionResult> EditAsync(EditConfigSiteInfo data, string name)
        {
            if (ModelState.IsValid)
            {
                string json = JsonSerializer.Serialize(data);
                Config config = new()
                {
                    Name = name,
                    Data = json,
                };
                await _configService.UpdateByNameAsync(config, name);
                await _logService.InsertLogSqlAsync(await UserInfoAsync(), "修改系统配置");
                return Json(new { status = 1, msg = "修改成功！" });
            }
            else
            {
                var error = ModelState.GetErrorMessages();
                return Json(new { status = 0, msg = error });
            }

        }
    }
}
